from django.shortcuts import render
from rest_framework.generics import ListAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView

from rest_framework.response import Response
from rest_framework_extensions.cache.decorators import cache_response
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from areas.serializers import AreasSerializer,AddressSerializers
from areas.models import Area


# Create your views here.

# 获取所有省信息
from users.models import Address


class AreasView(CacheResponseMixin,ListAPIView): # 获取多个信息
    serializer_class = AreasSerializer
    queryset = Area.objects.filter(parent=None)


# 获取所有市的信息和区县信息
 # CacheResponseMixin 缓存操作 写前边
class AreaView(CacheResponseMixin,ListAPIView):
    serializer_class = AreasSerializer

    # 使用缓存帮助MYSQL数据库分散压力  指定缓存时间/ 缓存那个数据库
    # @cache_response(timeout=60*60,cache='default')
    def get_queryset(self):
        pk = self.kwargs['pk'] #获取路由的pk值
        return Area.objects.filter(parent_id=pk)



# 保存地址
class AddressView(CreateAPIView,UpdateAPIView,ListAPIView):
    serializer_class = AddressSerializers

    # 重写get方法获取所有地址信息
    def get_queryset(self):
        return Address.objects.filter(user=self.request.user,is_deleted=False)


    # 重写删除地址信息
    def delete(self,request,pk):
        obj = self.get_object()
        obj.is_deleted = True
        obj.save()
        return Response()

    # 重写List方法返回数据的结果
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        # addresses：需要get获取这个数据 返回默认地址default_address_id
        return Response({'addresses':serializer.data,'default_address_id':self.request.user.default_address_id})
